var HubIconsSettingsView = Backbone.View.extend({
	el: '#dlgHubIconsSettings',

	events: {
		'click #btnApplySettings': 'applySettings'
	},

	initialize: function(){
		this.$toggleAddressIcon = this.$('#tbtnAddress'),
		this.$toggleRelationshipIcon = this.$('#tbtnRelationship'),
		this.$toggleNotesIcon = this.$('#tbtnNotes');

		$('.icons-button').toggleButtons({
	    	width: 140,
	    	style: {
	        	enabled: "success",
	        	disabled: "danger"
	    	},
	    	label: {
	        	enabled: "On",
	        	disabled: "Off"
	    	}
		});

		var hubIconsSettings = dashboard.getHubIconsSettings();
		this.$toggleAddressIcon.toggleButtons('setState', hubIconsSettings.Address);
		this.$toggleRelationshipIcon.toggleButtons('setState', hubIconsSettings.Relationship);
		this.$toggleNotesIcon.toggleButtons('setState', hubIconsSettings.Notes);		
	},

	render: function(){
		// we use data-toggle to pop up this view, so do nothing here
	},

	applySettings: function(){
		var addressOn = this.$toggleAddressIcon.toggleButtons('status'),
			relationshipOn = this.$toggleRelationshipIcon.toggleButtons('status'),
			notesOn = this.$toggleNotesIcon.toggleButtons('status');
		var icons = [];			
		if(addressOn){
			icons.push('Address');
		}
		if(relationshipOn){
			icons.push('Relationship');
		}
		if(notesOn){
			icons.push('Notes');
		}
		dashboard.configHubIcons(icons);
		this.trigger('hubIconsReConfigured');
	}
});

var DashboardView = Backbone.View.extend({
	el: '#mainbar',

	events: {
	},	

	initialize: function(){
		this.app = this.options.App;
		var templateString = $('#mainbarTemplate').text();
		this.template = _.template(templateString);	
	},

	render: function(customer) {	
		this.app.appView.renderHubIcons();	
		var html = this.template(customer);
		this.$el.html(html);		
	}
});

var AddressView = Backbone.View.extend({
	el: '#addressModal',

	initialize: function(){
		var me =  this;
		this.app = this.options.App;
		var addressTemplateString = $('#addressDetailTemplate').text();		
		this.template = _.template(addressTemplateString);

		this.$el.on('hidden', function(){
			me.app.navigate('#customer/' + dashboard.currentCustomer.Id);	
		})
	},

	render: function(customer) {
		var html = this.template(customer);
		this.$el.html(html).modal();
	},
});

var CommunicationView = Backbone.View.extend({
	el: 'div.matter',

	initialize: function(){
		var templateString = $('#communicationTemplate').text();
		this.template = _.template(templateString);
	},

	render: function(customer){
		var html = this.template(customer);
		$('div.matter').html(html);
	}
});

var FinancialTransactionsView = Backbone.View.extend({
	el: 'div.matter',

	initialize: function(){
		var templateString = $('#financialTransactionsTemplate').text();
		this.template = _.template(templateString);
	},

	render: function(customer){
		var html = this.template(customer);
		$('div.matter').html(html);
	}
});

var LoginView = Backbone.View.extend({
	el: '#loginPage',

	events: {
		'click #btnLogin': 'doLogin',
		'keyup #txtUser': 'checkSignable',
		'keyup #inputPassword': 'checkSignable'
	},

	initialize: function(){
		var me = this;
		this.$btnLogin = this.$el.find('#btnLogin');
		this.$txtUser = this.$el.find('#inputUser');
		this.$txtPassword = this.$el.find('#inputPassword');
		this.$cbRememberMe = this.$el.find('#inputRememberMe');

		this.checkSignable();

		this.on('logined', function(){
			me.close();
		});
	},

	render: function(){
		this.$el.show();
	},

	checkSignable: function(e){
		var email = $.trim(this.$txtUser.val());
		var pwd = $.trim(this.$txtPassword.val());
		if(email && pwd){
			this.$btnLogin.removeClass('disabled');
		}else {
			this.$btnLogin.addClass('disabled');
		}
		if(e && e.keyCode === 13){
			this.doLogin();
		}
	},

	doLogin: function(e){
		if(e)
			e.preventDefault();
		var user = $.trim(this.$txtUser.val());
		dashboard.username =user;

		if(this.$cbRememberMe.is(':checked')){
			window.localStorage.username = user;
		}		
		this.trigger('logined', user);
	},

	close: function(){
		this.$el.hide();
	}
});

var AppView = Backbone.View.extend({
	el: 'body',
	events: {
		'keyup #searchName': 'triggerSearch',
		'click #btnSearch': 'searchCustomer'		
	},

	initialize: function(){
		var me = this;
		this.app = this.options.App;
		this.$searchName = this.$('#searchName');
		this.$datalistCustomer = this.$('#customerNames');
		this.$lblUsername = this.$('#lblUsername');

		_.each(this.app.customers, function(customer){
				$('<option value="'+ customer.Details.FirstName + ' ' + customer.Details.Surname +'">').appendTo(me.$datalistCustomer);
		});	
	},

	triggerSearch: function(e){
		if(e.keyCode === 13){
			e.preventDefault();
			this.searchCustomer();
		}
	},

	searchCustomer: function(e){
		var searchByName = $.trim(this.$searchName.val());
		this.app.showDashboard(searchByName);		
	},

	render: function(){
		this.$el.find('>div.hide').not('#loginPage').show();
		this.$lblUsername.text(dashboard.username);
	},

	updateUsername: function(){
		this.$lblUsername.text(dashboard.username);
	},

	doLogout: function(){
		window.localStorage.removeItem('username');
		dashboard.username = null;
		this.$el.find('>div.hide').hide();
		this.app.loginView.render();
	},

	renderBreadCrumb: function(path){
		this.$('#hub-icons').hide();
		this.$('#bread-crumb').show();
		this.$('#bread-crumb .path').text(path);
	},

	renderHubIcons: function(){
		this.$('#hub-icons').show();
		this.$('#bread-crumb').hide();
	}
});



var App = Backbone.Router.extend({
	routes: {
	    "":                 		"home",
	    "login"				  :     "showLogin", 
	    "dashboard"	          :     "gotoDashboard",
	    "customer/:id"		  :     "showDashboard",
	    "customer/:id/address":     "showAddress",
	    "customer/:id/ft"	  :     "showFTList",
	    "ft"				  :     "showFTList",
	    "customer/:id/communication": "showCommunicationList",
	    "communication"             : "showCommunicationList"
	},

	initialize: function(customers){
		var me = this;
		this.customers = customers;	
		this.appView = new AppView({App: this});
		this.loginView = new LoginView({App: this});
		this.hubIconsSettingsView = new HubIconsSettingsView({App: this});
		this.dashboardView = new DashboardView({App: this});
		this.addressView = new AddressView({App: this});
		this.financialTransctionsView = new FinancialTransactionsView({App: this});
		this.communicationView = new CommunicationView({App: this});

		if(!dashboard.currentCustomer){			
			dashboard.currentCustomer = customers[0];
		}

		this.loginView.on('logined', function(data){
			me.showDashboard(dashboard.currentCustomer.Id);
			me.appView.render();
			dashboard.notify('content/img/user-big.png', 'Welcome ' + data, 'Today is ' + moment().format('MM/DD/YYYY')  + '.', 2500);
		});

		this.hubIconsSettingsView.on('hubIconsReConfigured', function(){			
			me.showDashboard(dashboard.currentCustomer.Id);
		});
	},

	showLogin: function(){
		this.appView.doLogout();
	},

	updateCustomerUrl: function(){
		this.navigate('#customer/' + dashboard.currentCustomer.Id);
	},

	home: function() {
		// Backbone has no route filter
		if(!dashboard.username){			
			this.navigate('#login', true);			
		}else{			
			this.loginView.trigger('logined', dashboard.username);
		}
	},

	gotoDashboard: function(){
		this.navigate('#customer/' + dashboard.currentCustomer.Id, true);
	},

	showDashboard: function(id) {
		// Backbone has no route filter
		if(!dashboard.username)	{
			this.navigate('#login', true);
			return;
		}
		var customer = this.searchCustomer(id);
		if(customer){
			this.appView.render();
			this.dashboardView.render(customer);
			this.updateCustomerUrl();
		}
	},

	showAddress: function(id) {
		var customer  = this.searchCustomer(id);
		if(customer){
			this.appView.render();
			this.dashboardView.render(customer);
			this.addressView.render(customer);
		}
	},

	searchCustomer: function(search){
		var customer = dashboard.getCustomer(search);
		if(!customer) {
			dashboard.notifyWarning('Customer ' + search + ' not found!');
			return;
		}
		dashboard.currentCustomer = customer;
		return customer;
	},

	showCommunicationList: function(id){
		if(!id) {
			this.navigate('#customer/' + dashboard.currentCustomer.Id + '/communication');	
		}
		else{
			var customer  = this.searchCustomer(id);
		}
		this.appView.render();
		this.appView.renderBreadCrumb('/ Marketing / Communications');
		this.communicationView.render(dashboard.currentCustomer);
	},

	showFTList: function(id){
		if(!id) {
			this.navigate('#customer/' + dashboard.currentCustomer.Id + '/ft');	
		}
		else{
			var customer  = this.searchCustomer(id);
		}
		this.appView.renderBreadCrumb('/ Finance / Transactions');
		this.financialTransctionsView.render(dashboard.currentCustomer);
	}
});

$(function(){
	var app = new App(window.customers);
	Backbone.history.start();	
});